package io.techery.properratingbar;

import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.render.layoutboost.LayoutBoostUtils;
import ohos.app.Context;
import ohos.agp.utils.Color;
import ohos.agp.text.Font;



/*
    The MIT License (MIT)

    Copyright (c) 2015 Techery (http://techery.io/)

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
 */

/**
 * DirectionalLayout
 */
public class ProperRatingBar extends DirectionalLayout {

    private static final int DF_TOTAL_TICKS = 5;
    private static final int DF_DEFAULT_TICKS = 3;
    private static final boolean DF_CLICKABLE = false;
    private static final int DF_SYMBOLIC_TICK_RES = ResourceTable.String_prb_default_symbolic_string;
    private static final int DF_SYMBOLIC_TEXT_SIZE_RES = ResourceTable.String_prb_symbolic_tick_default_text_size;
    private static final int DF_SYMBOLIC_TEXT_STYLE = Font.REGULAR;
    private static final Color DF_SYMBOLIC_TEXT_NORMAL_COLOR = Color.BLACK;
    private static final Color DF_SYMBOLIC_TEXT_SELECTED_COLOR = Color.GRAY;
    private static final int DF_TICK_SPACING_RES = ResourceTable.String_prb_drawable_tick_default_spacing;

    // font weight
    private static final int FONT_DEFAULT = 400;
    private static final int FONT_MEDUIM = 500;

    private int totalTicks;
    private int lastSelectedTickIndex;
    private boolean clickable;
    private String symbolicTick;
    private int customTextSize;
    private int customTextStyle;
    private Color customTextNormalColor;
    private Color customTextSelectedColor;
    private Element tickNormalDrawable;
    private Element tickSelectedDrawable;
    private int tickSpacing;

    private boolean useSymbolicTick = false;
    private int rating;
    private RatingListener listener = null;

    public ProperRatingBar(Context context, AttrSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttrSet attrs) {

        totalTicks = attrs.getAttr("prb_totalTicks").isPresent() ? attrs.getAttr("prb_totalTicks").get().getIntegerValue() : DF_TOTAL_TICKS;

        rating = attrs.getAttr("prb_defaultRating").isPresent() ? attrs.getAttr("prb_defaultRating").get().getIntegerValue() : DF_DEFAULT_TICKS;

        clickable = attrs.getAttr("prb_clickable").isPresent() ? attrs.getAttr("prb_clickable").get().getBoolValue() : DF_CLICKABLE;

        symbolicTick = attrs.getAttr("prb_symbolicTick").isPresent() ? attrs.getAttr("prb_symbolicTick").get().getStringValue() : context.getString(DF_SYMBOLIC_TICK_RES);

        customTextSize = attrs.getAttr("text_size").isPresent() ? attrs.getAttr("text_size").get().getDimensionValue() : LayoutBoostUtils.getDimensionValue(context, context.getString(DF_SYMBOLIC_TEXT_SIZE_RES));

        customTextStyle = attrs.getAttr("text_weight").isPresent() ? attrs.getAttr("text_weight").get().getIntegerValue() : DF_SYMBOLIC_TEXT_STYLE;

        customTextNormalColor = attrs.getAttr("prb_symbolicTickNormalColor").isPresent() ? attrs.getAttr("prb_symbolicTickNormalColor").get().getColorValue() : DF_SYMBOLIC_TEXT_NORMAL_COLOR;

        customTextSelectedColor = attrs.getAttr("prb_symbolicTickSelectedColor").isPresent() ? attrs.getAttr("prb_symbolicTickSelectedColor").get().getColorValue() : DF_SYMBOLIC_TEXT_SELECTED_COLOR;

        tickNormalDrawable = attrs.getAttr("prb_tickNormalDrawable").isPresent() ? attrs.getAttr("prb_tickNormalDrawable").get().getElement() : null;

        tickSelectedDrawable = attrs.getAttr("prb_tickSelectedDrawable").isPresent() ? attrs.getAttr("prb_tickSelectedDrawable").get().getElement() : null;

        tickSpacing = attrs.getAttr("prb_tickSpacing").isPresent() ? attrs.getAttr("prb_tickSpacing").get().getDimensionValue() : LayoutBoostUtils.getDimensionValue(context, context.getString(DF_TICK_SPACING_RES));

        afterInit();

    }

    private void afterInit() {
        if (rating > totalTicks) {
            rating = totalTicks;
        }
        lastSelectedTickIndex = rating - 1;
        //判断是否有图片
        if (tickNormalDrawable == null || tickSelectedDrawable == null) {
            useSymbolicTick = true;
        }
        //添加
        addTicks(this.getContext());
    }

    private void addTicks(Context context) {
        this.removeAllComponents();
        for (int i = 0; i < totalTicks; i++) {
            addTick(context, i);
        }
        redrawTicks();
    }

    private void addTick(Context context, int position) {
        if (useSymbolicTick) {
            // 添加符号
            addSymbolicTick(context, position);
        } else {
            // 添加图片的
            addDrawableTick(context, position);
        }
    }

    // 添加符号
    private void addSymbolicTick(Context context, int position) {
        Text tv = new Text(context);
        tv.setText(symbolicTick);
        tv.setTextSize(customTextSize);

        // 设置字体粗细
        if (customTextStyle != FONT_DEFAULT) {  // 原来0-默认，现在400
            Font fontStyle = Font.DEFAULT;
            if (customTextStyle > FONT_MEDUIM) {
                fontStyle = Font.DEFAULT_BOLD;
            }
            tv.setFont(fontStyle);
        }
        updateTicksClickParameters(tv, position);
        this.addComponent(tv);
    }

    // 添加图片的
    private void addDrawableTick(Context context, int position) {
        Image iv = new Image(context);
        iv.setPadding(tickSpacing, tickSpacing, tickSpacing, tickSpacing);
        updateTicksClickParameters(iv, position);
        this.addComponent(iv);
    }

    private void updateTicksClickParameters(Component tick, int position) {
        if (clickable) {
            tick.setTag(position);
            tick.setClickedListener(mTickClickedListener);
        } else {
            tick.setClickedListener(null);
        }
    }

    private Component.ClickedListener mTickClickedListener = new ClickedListener() {
        @Override
        public void onClick(Component v) {
            lastSelectedTickIndex = (int) v.getTag();
            rating = lastSelectedTickIndex + 1;
            redrawTicks();
            if (listener != null) {
                listener.onRatePicked(ProperRatingBar.this);
            }
        }
    };

    // 重新描绘 ok
    private void redrawTicks() {
        iterateTicks(new TicksIterator() {
            @Override
            public void onTick(Component tick, int position) {
                if (useSymbolicTick) {
                    redrawTickSelection((Text) tick,
                            position <= lastSelectedTickIndex);
                } else {
                    redrawTickSelection((Image) tick,
                            position <= lastSelectedTickIndex);
                }
            }
        });
    }

    private void redrawTickSelection(Image tick, boolean isSelected) {
        if (isSelected) {
            tick.setImageElement(tickSelectedDrawable);
        } else {
            tick.setImageElement(tickNormalDrawable);
        }
    }

    private void redrawTickSelection(Text tick, boolean isSelected) {
        if (isSelected) {
            tick.setTextColor(customTextSelectedColor);
        } else {
            tick.setTextColor(customTextNormalColor);
        }
    }

    private void iterateTicks(TicksIterator iterator) {
        if (iterator == null) {
            throw new IllegalArgumentException("Iterator can't be null!");
        }

        for (int i = 0; i < getChildCount(); i++) {
            iterator.onTick(getComponentAt(i), i);
        }
    }

    private interface TicksIterator {
        void onTick(Component tick, int position);
    }


    ///////////////////////////////////////////////////////////////////////////
    // Essential public methods
    ///////////////////////////////////////////////////////////////////////////

    public boolean isClickable() {
        return clickable;
    }

    /**
     * Nifty sugar method to just toggle clickable to opposite state.
     */
    public void toggleClickable() {
        setClickable(!clickable);
    }

    public void setClickable(boolean clickable) {
        this.clickable = clickable;
        iterateTicks(new TicksIterator() {
            @Override
            public void onTick(Component tick, int position) {
                updateTicksClickParameters(tick, position);
            }
        });
    }

    /**
     * Get the attached {@link RatingListener}
     *
     * @return listener or null if none was set
     */
    public RatingListener getListener() {
        return listener;
    }

    /**
     * Set the {@link RatingListener} to be called when user taps rating bar's ticks
     *
     * @param listener listener to set
     * @throws IllegalArgumentException if listener is <b>null</b>
     */
    public void setListener(RatingListener listener) {
        if (listener == null) {
            throw new IllegalArgumentException("listener cannot be null!");
        }

        this.listener = listener;
    }

    /**
     * Remove listener
     */
    public void removeRatingListener() {
        this.listener = null;
    }

    /**
     * Get the current rating shown
     *
     * @return rating
     */
    public int getRating() {
        return rating;
    }

    /**
     * Set the rating to show
     *
     * @param rating new rating value
     */
    public void setRating(int rating) {
        if (rating > this.totalTicks) {
            rating = totalTicks;
        }
        this.rating = rating;
        lastSelectedTickIndex = rating - 1;
        redrawTicks();
    }

    public void setSymbolicTick(String tick) {
        this.symbolicTick = tick;
        afterInit();
    }

    public String getSymbolicTick() {
        return this.symbolicTick;
    }
}
